<?php

namespace app\admin\controller\zbtask;

use app\admin\logic\DelLogic;
use app\common\controller\Backend;
use think\Db;
use think\exception\ValidateException;

/**
 * 任务订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\common\model\zbtask\Order
     */
    protected $model = null;
    //做了数据限制
    protected $dataLimit = 'auth';
    protected $dataLimitField = 'company_id';
    protected $dataLimitFieldAutoFill = false;

    /**
     * 获取数据限制的管理员ID
     * 禁用数据限制时返回的是null
     * @return mixed
     */
    protected function getDataLimitAdminIds()
    {
        if (!$this->dataLimit) {
            return null;
        }
        //超级管理员
        if ($this->auth->isSuperAdmin() || TYPE == 0) {
            return null;
        }
        if (TYPE == 1) {
            return [TYPE_ID];
        }else if (TYPE == 2) {
            $this->error('不能查看订单');
        }
    }

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\zbtask\Order;
        $this->view->assign("isSubmitList", $this->model->getIsSubmitList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isJiesuanList", $this->model->getIsJiesuanList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $this->searchFields = 'user.real_name,zbtask.name';
      //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['zbtask','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['zbtask','user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','user_id','task_id','is_submit','type','createtime','status','submittime','paytime','droptime','is_jiesuan','send_time']);
                $row->visible(['zbtask']);
				$row->getRelation('zbtask')->visible(['id','name']);
				$row->visible(['user']);
				$row->getRelation('user')->visible(['id','real_name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除订单
     */
    public function del($ids = "")
    {

        if ($ids) {
            //开启了数据限制 只能删除和查询自己的 如果是管理员 都可以删除
            $adminIds = $this->getDataLimitAdminIds();

            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where('id', 'in', $ids)->select();
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    //如果已结算那么订单不能删除
                    if ($v['is_jiesuan'] == 1) {
                        throw new ValidateException('订单已结算不能删除');
                    }
                    DelLogic::instance()->order($v['id']);  //删除逻辑
                    $count += $v->delete();
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
}
